import re

from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.libs.image_storage import storage
from info.models import User, House
from info.modules.profile import profile_blu
from info.utils.common import user_login
from info.utils.response_code import RET


# 苏印戳
@profile_blu.route("/houses")
@user_login
def houses():
    """
    我的房源
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    houses_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = House.query.filter(House.user_id == user.id).order_by(House.price.asc()).paginate(page, constants.MY_HOUSE_PAGE_MAX, False)
        houses_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    houses_dict_li = []
    for houses_obj in houses_list:
        houses_dict_li.append(houses_obj.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="OK",data = houses_dict_li)


@profile_blu.route("/auth", methods=["POST", "GET"])
@user_login
def auth():
    """
    实名认证
    :return:
    """
    user = g.user
    if request.method == "GET":
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

        data = {
            "real_name":user.real_name,
            "id_card":user.id_card
        }
        return jsonify(errno=RET.OK, errmsg="OK",data=data)
    real_name = request.json.get("real_name")
    id_card = request.json.get("id_card")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if not all([real_name,id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not re.match('^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$', real_name):
        return jsonify(errno=RET.PARAMERR, errmsg="姓名格式不正确")
    if not re.match('(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)', id_card):
        return jsonify(errno=RET.PARAMERR, errmsg="身份证号格式不正确")
    user.real_name = real_name
    user.id_card = id_card
    try:
        db.session.commit()
        return jsonify(errno=RET.OK, errmsg="ok")
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")


# 甘宇飞
@profile_blu.route("/avatar", methods=["POST"])
@user_login
def upload_avatar():
    """
    更新头像
    """
    user = g.user
    # 判断上传文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="请选择图片")

    # 将用户上传的图像 保存在七牛云上
    try:
        key = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="上传头像成功", data=constants.QINIU_DOMIN_PREFIX + key)


@profile_blu.route("/name", methods=["POST"])
@user_login
def set_user_name():
    """
    设置用户名
    :return:
    """
    user = g.user
    name = request.json.get("name")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    user.name = name
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户名失败")

    return jsonify(errno=RET.OK, errmsg="修改成功")

